package com.heba.adapter;

import androidx.recyclerview.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.heba.utils.UniversalImageLoadTool;

import java.util.List;

/**
 * RecyclerView万能适配器
 * <p>
 * Created by jason on 2018/10/25.
 */

public abstract class QuickAdapter<T> extends RecyclerView.Adapter<QuickAdapter.VH> {

    private List<T> mDatas;

    public QuickAdapter(List<T> datas) {
        this.mDatas = datas;
    }

    public abstract int getLayoutId(int viewType);

    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return VH.get(parent, getLayoutId(viewType));
    }

    @Override
    public void onBindViewHolder(VH holder, int position) {
        convert(holder, mDatas.get(position), position);
    }


    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    public abstract void convert(VH holder, T data, int position);

    public static class VH extends RecyclerView.ViewHolder {
        private SparseArray<View> mViews;
        private View mConvertView;

        private VH(View v) {
            super(v);
            mConvertView = v;
            mViews = new SparseArray<>();
        }

        public static VH get(ViewGroup parent, int layoutId) {
            View convertView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
            return new VH(convertView);
        }

        public <T extends View> T getView(int id) {
            View v = mViews.get(id);
            if (v == null) {
                v = mConvertView.findViewById(id);
                mViews.put(id, v);
            }
            return (T) v;
        }

        /**
         * 设置文字内容
         *
         * @param id
         * @param value
         */
        public void setText(int id, String value) {
            TextView view = getView(id);
            view.setText(value);
        }

        /**
         * 设置图片资源
         *
         * @param id
         * @param imageId
         */
        public void setImage(int id, int imageId) {
            ImageView view = getView(id);
            view.setImageResource(imageId);
        }

        /**
         * 加載圖片
         *
         * @param id
         * @param imgUrl
         */
        public void setImageFromUrl(int id, String imgUrl) {
            ImageView view = getView(id);
            UniversalImageLoadTool.disPlay(imgUrl, view);
        }

        /**
         * 加載圖片
         *
         * @param id
         * @param imgUrl
         * @param defaultId 加載時顯示的默認圖片
         */
        public void setImageFromUrlWithDefault(int id, String imgUrl, int defaultId) {
            ImageView view = getView(id);
            UniversalImageLoadTool.disPlay(imgUrl, view, defaultId);
        }
    }
}
